package com.sun.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.config.Result;
import com.sun.entity.User;
import com.sun.service.UserService;


import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SimpleTimeZone;

@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@GetMapping("/getUser/{id}")
	public Result selectById(@PathVariable("id") Long id) throws Exception {

		return  Result.success(userService.selectUserById(id));
	}

	/**
	 * 查询所有用户后显示到 ulist页面
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/getUserList")
	public String getUserList(@RequestParam(defaultValue = "1") int page,
							  @RequestParam(defaultValue = "5") int size,
							Model model,@ModelAttribute("msg") String msg ,
							HttpSession session , User user) throws Exception {

		PageInfo<User> pageInfo = userService.getUserByPage(page, size);
		// List<User> userList = userService.getUserList();
		model.addAttribute("ulist",pageInfo.getList()); // 当前页的数据
		model.addAttribute("pageInfo", pageInfo);        // 分页信息对象
		if (msg != null && !msg.isEmpty()) {
			model.addAttribute("msg", msg);
		}
		// 从Session中获取当前登录用户

		return "ulist";
	}

	@PutMapping("/updateByid/{id}")
	public User updateByid(@PathVariable Long id, @RequestBody User user) throws Exception {
		user.setId(id);
		return userService.updateByid(id, user);
	}

	@DeleteMapping("/deletByid/{id}")
	public void deletByid(@PathVariable Long id){
		userService.deleteByid(id);
	}



/*	@PostMapping("/addUser")
	public String addUser(User user){
		int num=userService.addUser(user);
		if(num>0)
			return "success";
		else
			return "error";
	}*/

	/**
	 * 查看用户信息
	 * @param id
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/userShow/{id}")
	public String showDetail(@PathVariable("id") Long id , Model model, HttpSession session) throws Exception {
		User user =  userService.showDetail(id);
		model.addAttribute("user",user);
		// 从Session中获取当前登录用户

		return  "detail";
	}

	/**
	 * 删除用户信息
	 * @param id
	 * @param
	 * @return
	 */
	@RequestMapping("/userDel/{id}")
	public String userDel(@PathVariable("id") Long id ,RedirectAttributes redirectAttributes){
		int num  = userService.userDelByid(id);
		redirectAttributes.addFlashAttribute("msg", num > 0 ? "删除成功！" : "删除失败！");
		return "redirect:/getUserList"; // 改用重定向
	}

	/**
	 * 对用户的信息修改，跳转到修改页面，和前面展示用户信息相似
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/toUpdateUser/{id}")
	public String toUpdateUser(@PathVariable("id") Long id , Model model, HttpSession session){
		User user = userService.showDetail(id);
		model.addAttribute("user",user);
		// 从Session中获取当前登录用户

		return "userUpdate";

	}

	/**
	 * 更新用户
	 * @param
	 * @param user
	 * @return
	 * @throws Exception
	 */

	@RequestMapping("/updateUser")
	public String updateUser( User user , Model model,RedirectAttributes redirectAttributes) {
		int num =	userService.updateUser(user);
		redirectAttributes.addFlashAttribute("msg", num > 0 ? "修改成功！" : "修改失败！");
		return "redirect:/getUserList"; // 改用重定向
	}

	/**
	 * 去到添加用户的界面，并且传入当前用户的登录name属性
	 * @param model
	 * @param session
	 * @return
	 */
	@GetMapping("/toAddUser")
	public String toAddUser( Model model, HttpSession session){
		// 从Session中获取当前登录用户

		return "userAdd";

	}

	/**
	 * 增加功能，添加一个用户
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping("/addUser")
	public String adduser(User user, Model model,RedirectAttributes redirectAttributes){
		int num = userService.addUser(user);
		redirectAttributes.addFlashAttribute("msg", num > 0 ? "添加成功！" : "添加失败！");
		return "redirect:/getUserList"; // 改用重定向
	}

	/*@GetMapping
	public PageInfo<User> getUsers(@RequestParam(defaultValue = "1")int page ,
								   @RequestParam(defaultValue = "5")int size){
		return userService.getUserByPage(page,size);
	}*/

	// 搜索用户（分页）
	@PostMapping("/searchUser")
	public String searchUser(
			@RequestParam("searchTerm") String searchTerm,
			@RequestParam(defaultValue = "1") int pageNum,
			@RequestParam(defaultValue = "8") int pageSize,
			Model model
	) {
		PageInfo<User> pageInfo = userService.searchUsersPage(searchTerm, pageNum, pageSize);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("ulist", pageInfo.getList());
		return "ulist"; // 返回用户列表页面
	}

	/**
	 * 批量删除
	 * @param request
	 * @return
	 */
	@PostMapping("/batchDelete")
	@ResponseBody  // 添加这个注解确保返回JSON
	public ResponseEntity<Map<String , Object>> batchDeleteUsers(@RequestBody Map<String,List<Long>> request){
		System.out.println("=== 请求到达 ===");
		System.out.println("接收到的ID列表: " + request.get("ids"));
		Map<String , Object> response = new HashMap<>();
		try {
			List<Long> ids = request.get("ids");
			if (ids == null || ids.isEmpty()) {
				response.put("success", false);
				response.put("message", "未提供要删除的用户ID");
				return ResponseEntity.badRequest().body(response);
			}

			int deleteCount = userService.batchDeleteUsers(ids);

			response.put("success", true);
			response.put("message", "成功删除" + deleteCount + "条用户记录");
			response.put("deleteCount", deleteCount);
			return ResponseEntity.ok(response);
		} catch (Exception e){
			response.put("success",false);
			response.put("message","批量删除失败:" + e.getMessage());
			return ResponseEntity.internalServerError().body(response);
		}
	}
}